import { CACHE_USERINFO, CACHE_TOKEN, CACHE_EXPIRES_TIME } from '../../config.js';
import Util from '../../utils/util.js';
import { login } from '../../api/user.js';

let app = getApp();

Component({
  properties: {
    isHidden: {
      type: Boolean,
      value: true,
    },
    //是否自动登录
    isAuto: {
      type: Boolean,
      value: true,
    },
    isGoLogin: {
      type: Boolean,
      value: true,
    },
  },
  data: {
    cloneIner: null,
    loading: false,
    errorSum: 0,
    errorNum: 3
  },
  attached() {
    this.setAuthStatus();
  },
  methods: {
    //检测登录状态并执行自动登录
    setAuthStatus() {
      var that = this;
      Util.chekWxLogin().then((res) => {
        let pages = getCurrentPages();
        let currPage = pages[pages.length - 1];
        if (currPage && currPage.data.isHidden != undefined) {
          currPage.setData({ isHidden: true });
        }
        if (res.isLogin) {
          if (!Util.checkLogin()) return Promise.reject({ authSetting: true, msg: '用户token失效', userInfo: res.userInfo });
          that.triggerEvent('onLoadFun', app.globalData.userInfo);
        } else {
          wx.showLoading({ title: '正在加载中' });
          that.setUserInfo(res.userInfo, false);
        }
      }).catch(res => {
        if (res.authSetting === false) {
          //没有授权不会自动弹出登录框
          if (that.data.isAuto === false) return;
          //自动弹出授权
          that.gotoLogin();
        } else if (res.authSetting) {
          //授权后登录token失效了
          that.setUserInfo(res.userInfo);
        }
      })
    },
    //授权
    setUserInfo(userInfo, isLogin) {
      let that = this;
      wx.showLoading({ title: '正在加载中' });
      if (isLogin) {
        // 用户已登陆，不做处理
        wx.hideLoading();
        that.close();
        //that.getWxUserInfo(userInfo);
      } else {
        Util.getCodeLogin((res) => {
          Util.wxgetUserInfo().then(userInfo => {
            userInfo.code = res.code;
            that.getWxUserInfo(userInfo);
          }).catch(res => {
            wx.hideLoading();
          });
        });
      }
    },
    /** 去登陆页面 */
    gotoLogin: function () {
      if (this.data.isGoLogin === true) {
        wx.navigateTo({
          url: '/pages/login/login',
        });
      } else {
        this.setData({ isHidden: false });
      }
    },
    getWxUserInfo: function (userInfo) {
      let that = this;
      var args = {
        code: userInfo.code,
        sessionKey: userInfo.cache_key || '',
        encryptedData: userInfo.encryptedData,
        iv: userInfo.iv,
        rawData: userInfo.rawData,
        signature: userInfo.signature
      }
      login(args).then(res => {
        app.globalData.token = res.token;
        app.globalData.userType = res.userInfo.userType;
        app.globalData.isLogin = true;
        app.globalData.userInfo = res.userInfo;
        if (res.sessionKey) wx.setStorage({ key: 'cache_key', data: res.sessionKey });
        //取消登录提示
        wx.hideLoading();
        //关闭登录弹出窗口
        that.setData({ isHidden: true, errorSum: 0 });
        // 判断是否绑定用户，如未绑定。跳转登陆页
        if (res.isBind === 1 || that.data.isGoLogin === false) {
          //执行登录完成回调
          that.triggerEvent('onLoadFun', res);
        } else {
          if (this.data.isGoLogin) {
            wx.navigateTo({
              url: '/pages/login/login',
            });
          } else {
            that.triggerEvent('onLoadFun', res);
          }
        }
      }).catch((err) => {
        wx.hideLoading();
        that.data.errorSum++;
        that.setData({ errorSum: that.data.errorSum });
        if (that.data.errorSum >= that.data.errorNum) {
          // Util.Tips({ title: err });
          console.log(err);
        } else {
          that.setUserInfo(userInfo);
        }
      });
    }
  }
})